package com.ccsu.mymarket.controller;

import com.ccsu.mymarket.entity.DeliveryAddress;
import com.ccsu.mymarket.entity.message.Meta;
import com.ccsu.mymarket.entity.message.Result;
import com.ccsu.mymarket.jwt.UserLoginToken;
import com.ccsu.mymarket.service.DeliveryAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@UserLoginToken
@RestController
@RequestMapping("/address")
public class DeliveryAdressController {
    private final DeliveryAddressService addressService;

    public DeliveryAdressController(@Autowired DeliveryAddressService addressService) {
        this.addressService = addressService;
    }


    @GetMapping("/page/{id}")
// 传入用户 id
    public Result getAddressByUser(@PathVariable Integer id){
        List<DeliveryAddress> addressList=addressService.getAddressByUser(id);
        if (addressList==null)
            return new Result(new Meta(201,"暂无数据"),null);
        return new Result(new Meta(200,"查询成功！"),addressList);
    }

    @PostMapping("/add")
//    以DeliveryAddress实体类格式传入所有数据
    public Result addAdress(@RequestBody DeliveryAddress address){
        if (address==null || address.getAccId()==null)
            return new Result(new Meta(403,"数据非法！"),null);
        if (addressService.save(address))
            return new Result(new Meta(200,"成功新增收货地址！"),null);
        return new Result(new Meta(500,"操作失败！"),null);
    }

    @DeleteMapping("/delete/{id}")
//    传入id
    public Result deleteAdress(@PathVariable Integer id){
        if (addressService.removeById(id))
            return new Result(new Meta(200,"删除成功！"),null);
        return new Result(new Meta(500,"操作失败！"),null);
    }

    @PutMapping("/update")
//    以DeliveryAddress实体类格式传入所有数据
    public Result updateAdress(@RequestBody DeliveryAddress address){
        if (address==null || address.getAccId()==null)
            return new Result(new Meta(403,"数据非法！"),null);
        if (addressService.updateById(address))
            return new Result(new Meta(200,"修改成功！"),null);
        return new Result(new Meta(500,"操作失败！"),null);
    }
}
